package com.server;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

public class OutputWorker implements Runnable {
	private Socket socket;

	public OutputWorker(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		OutputStream outputStream = null;
		BufferedReader buffer = null;
		try {
			InputStream inputStream = socket.getInputStream();
			buffer = new BufferedReader(new InputStreamReader(inputStream));
			String readLine = buffer.readLine();
			int indexOf = readLine.indexOf("/", 0);
			String substring = readLine.substring(indexOf);
			int indexOf2 = substring.indexOf(" ", 0);
			String substring3 = substring.substring(1, indexOf2);
			File file = new File("F:/HTML/");
			outputStream = socket.getOutputStream();
			getFile(file, substring3, outputStream);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				socket.close();
				buffer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	public void getFile(File file, String substring3, OutputStream outputStream) {
		File[] listFiles = file.listFiles();
		for (File file2 : listFiles) {
			if (file2.isFile()) {
				if (file2.getName().startsWith(substring3)) {
					if (file2.getName().endsWith(".html")) {
						byte[] data = new byte[1024];
						BufferedInputStream buff = null;
						BufferedOutputStream bo = null;
						try {
							buff = new BufferedInputStream(new FileInputStream(
									"F:/HTML/" + file2.getName()));
							bo = new BufferedOutputStream(outputStream);
							int size = 0;
							while ((size = buff.read(data)) >= 0) {
								bo.write(data, 0, size);
							}
						} catch (FileNotFoundException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						} finally {
							try {
								buff.close();
								bo.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					}
				}
			}
		}
	}
}